package com.chain.BrotherExchange.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.LegalTenderAppealOrderInfo;
import com.chain.BrotherExchange.event.SubmitAppealSuccessEvent;
import com.chain.BrotherExchange.ui.core.BaseActivity;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.viewmodel.FeedbackViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 申诉
 */
public class LegalTenderAppealActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    @Bind(R.id.apply_button) Button applyButton;
    @Bind(R.id.add_image_layout) View mAddImageLayout;
    @Bind(R.id.direction_text) TextView directionText;
    @Bind(R.id.token_name_text) TextView tokenNameText;
    @Bind(R.id.order_number_text) TextView orderNumberText;
    @Bind(R.id.mobile_phone_text) TextView mobilePhoneText;
    @Bind(R.id.first_feedback_image) ImageView firstFeedbackImage;
    @Bind(R.id.second_feedback_image) ImageView secondFeedbackImage;
    @Bind(R.id.thirdly_feedback_image) ImageView thirdlyFeedbackImage;
    @Bind(R.id.feedback_content_edit) EditText mFeedbackContentEditText;

    private FeedbackViewModel mFeedbackViewModel;
    private LegalTenderAppealOrderInfo mOrderInfo;
    private List<ImageView> mImageViewList = new ArrayList<>();
    private Uri mFirstFeedbackImageUri, mSecondFeedbackImageUri, mThirdlyFeedbackImageUri;

    public static void launch(Context context, LegalTenderAppealOrderInfo orderInfo, int position) {
        context.startActivity(new Intent(context, LegalTenderAppealActivity.class)
                .putExtra(C.EXTRA_APPEAL_INFO, orderInfo)
                .putExtra(C.EXTRA_POSITION, position)
        );
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_order_appeal;
    }

    @Override
    protected void initActions() {
        ActivityBarHelper.init(this, R.string.appeal);

        // view model
        mFeedbackViewModel = ViewModelProviders.of(this).get(FeedbackViewModel.class);

        // 订单信息
        mOrderInfo = (LegalTenderAppealOrderInfo) getIntent()
                .getSerializableExtra(C.EXTRA_APPEAL_INFO);
        orderNumberText.setText(mOrderInfo.getOrderId());
        tokenNameText.setText(mOrderInfo.getTokenName());
        mobilePhoneText.setText(Androids.LocalConfig.getPhone());
        directionText.setText(mOrderInfo.getDirection() == C.API_PURCHASE
                ? getString(R.string.buy_ins) : getString(R.string.sale));
        mAddImageLayout.setOnClickListener(v -> requestPermission());

        // 反馈
        applyButton.setOnClickListener(v -> submitAppeal());
    }

    private void submitAppeal() {
        String feedback = mFeedbackContentEditText.getText().toString();
        mFeedbackViewModel.legalTenderAppeal(mOrderInfo.getTokenId(), mOrderInfo.getOrderId(),
                mOrderInfo.getDirection(), mOrderInfo.getTokenName(), feedback)
                .observe(this, resource -> {
                    if (resource.state == Resource.Status.LOADING) {
                        Androids.showProgressMessage(this, getString(R.string.submitting_an_appeal));
                    } else {
                        Androids.dismissProgressMessage();
                        Androids.makeText(resource.message);
                        if (resource.state == Resource.Status.SUCCESS) {
                            EventBus.getDefault().post(new SubmitAppealSuccessEvent(getIntent()
                                    .getIntExtra(C.EXTRA_POSITION, -1), resource.source.getData().getAppeal_id()));
                            finish();
                        }
                    }
                });
    }

    private void uploadImage(ImageView imageView) {
        mFeedbackViewModel.uploadFile(imageView).observe(this, resource -> {
            if (resource.state == Resource.Status.LOADING) {
                Androids.showProgressMessage(this, getString(R.string.upload_image));
            } else {
                Androids.dismissProgressMessage();
                Androids.makeText(resource.message);
            }
        });
    }

    private void requestPermission() {
        String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, permissions)) {
            String rationale = getString(R.string.please_approve_camera_permissions);
            EasyPermissions.requestPermissions(this, rationale, 0, permissions);
        } else {
            selectFeedbackImages();
        }
    }

    private void selectFeedbackImages() {
        Matisse.from(this)
                .choose(MimeType.allOf())
                .countable(true)
                .maxSelectable(1)
                .theme(R.style.Matisse_UNT)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(C.REQ_CHOOSE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            selectFeedbackImages();
        } else if (requestCode == C.REQ_CHOOSE && resultCode == RESULT_OK) {
            if (mFirstFeedbackImageUri == null) {
                mFirstFeedbackImageUri = Matisse.obtainResult(data).get(0);
                firstFeedbackImage.setImageURI(mFirstFeedbackImageUri);
                mImageViewList.add(firstFeedbackImage);
                uploadImage(firstFeedbackImage);
            } else if (mSecondFeedbackImageUri == null) {
                mSecondFeedbackImageUri = Matisse.obtainResult(data).get(0);
                secondFeedbackImage.setImageURI(mSecondFeedbackImageUri);
                mImageViewList.add(secondFeedbackImage);
                uploadImage(secondFeedbackImage);
            } else if (mThirdlyFeedbackImageUri == null) {
                mThirdlyFeedbackImageUri = Matisse.obtainResult(data).get(0);
                thirdlyFeedbackImage.setImageURI(mThirdlyFeedbackImageUri);
                thirdlyFeedbackImage.setVisibility(View.VISIBLE);
                mImageViewList.add(thirdlyFeedbackImage);
                mAddImageLayout.setVisibility(View.GONE);
                uploadImage(thirdlyFeedbackImage);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        selectFeedbackImages();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(R.string.auto_authorization_failure)
                    .setRationale(R.string.please_manually_select_approve_camera_permissions).build().show();
        } else {
            Androids.makeText(R.string.authorization_failure);
        }
    }
}
